package org.example;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static User currentUser = null;

    public static void main(String[] args) {
        while (true) {
            if (currentUser == null) {
                showMainMenu();
            } else {
                showUserMenu();
            }
        }
    }

    private static void showMainMenu() {
        System.out.println("\n-- 超市管理系统 --");
        System.out.println("1. 注册");
        System.out.println("2. 登录");
        System.out.println("3. 退出系统");
        System.out.print("请选择操作：");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                registerUser();
                break;
            case 2:
                loginUser();
                break;
            case 3:
                System.exit(0);
            default:
                System.out.println("无效的输入！");
        }
    }

    private static void showUserMenu() {
        System.out.println("\n-- 用户菜单 --");
        System.out.println("1. 查看所有商品");
        System.out.println("2. 购买商品");
        System.out.println("3. 查询我的订单");
        System.out.println("4. 搜索商品");
        System.out.println("5. 退出登录");
        System.out.print("请选择操作：");

        int choice = scanner.nextInt();
        scanner.nextLine();  // 消耗换行符

        switch (choice) {
            case 1:
                showAllProducts();
                break;
            case 2:
                purchaseProduct();
                break;
            case 3:
                showUserOrders();
                break;
            case 4:
                searchProduct();
                break;
            case 5:
                currentUser = null;
                System.out.println("已退出登录");
                break;
            default:
                System.out.println("无效的输入！");
        }
    }

    private static void registerUser() {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();
        System.out.print("请输入地址：");
        String address = scanner.nextLine();
        System.out.print("请输入电话：");
        String phone = scanner.nextLine();

        boolean success = DatabaseOperations.addUser(username, password, address, phone);
        System.out.println(success ? "注册成功！" : "注册失败！");
    }

    private static void loginUser() {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();

        User user = DatabaseOperations.getUser(username, null);
        if (user != null && user.getPassword().equals(password)) {
            currentUser = user;
            System.out.println("登录成功！");
        } else {
            System.out.println("用户名或密码错误！");
        }
    }

    private static void showAllProducts() {
        System.out.println("\n-- 所有商品 --");
        List<Product> products = DatabaseOperations.getAllProducts(); // 直接调用
        products.forEach(p -> System.out.printf("ID:%-4d 名称:%-20s 价格:%-6.2f 库存:%d\n",
                p.getProductId(), p.getName(), p.getPrice(), p.getStock()));
    }

    private static List<Product> getAllProducts() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Product> productList = new ArrayList<>();

        try {
            conn = Util.getConn();
            stmt = conn.createStatement();
            String sql = "SELECT * FROM product";
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
                Product product = new Product();
                product.setProductId(rs.getInt("product_id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                product.setStock(rs.getInt("stock"));
                productList.add(product);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Util.close(conn, stmt, rs);
        }
        return productList;
    }

    private static void purchaseProduct() {
        showAllProducts();
        System.out.print("请输入要购买的商品ID：");
        int productId = scanner.nextInt();
        System.out.print("请输入购买数量：");
        int quantity = scanner.nextInt();
        scanner.nextLine();  // 消耗换行符

        Product product = DatabaseOperations.getProduct(null, productId);
        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }

        if (product.getStock() < quantity) {
            System.out.println("库存不足！");
            return;
        }

        // 更新库存
        updateProductStock(productId, product.getStock() - quantity);

        // 创建订单
        createOrder(productId, quantity, product.getPrice() * quantity);
        System.out.println("购买成功！");
    }

    private static void updateProductStock(int productId, int newStock) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = Util.getConn();
            String sql = "UPDATE product SET stock = ? WHERE product_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, newStock);
            pstmt.setInt(2, productId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Util.close(conn, pstmt, null);
        }
    }

    private static void createOrder(int productId, int quantity, double totalAmount) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = Util.getConn();
            String sql = "INSERT INTO `order` (user_id, product_id, order_time, total_amount) VALUES (?, ?, NOW(), ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, currentUser.getUserId());
            pstmt.setInt(2, productId);
            pstmt.setDouble(3, totalAmount);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Util.close(conn, pstmt, null);
        }
    }

    private static void showUserOrders() {
        System.out.println("\n-- 我的订单 --");
        List<OrderDetail> orders = DatabaseOperations.getOrdersByUser(currentUser.getUserId());

        if (orders.isEmpty()) {
            System.out.println("暂无订单记录");
            return;
        }

        orders.forEach(o -> System.out.printf("订单ID:%-4d 商品:%-15s 时间:%tF %tT 总金额:%.2f\n",
                o.getOrderId(), o.getProductName(), o.getOrderTime(), o.getOrderTime(), o.getTotalAmount()));
    }

    private static void searchProduct() {
        System.out.print("请输入商品名称关键字：");
        String keyword = scanner.nextLine();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = Util.getConn();
            String sql = "SELECT * FROM product WHERE name LIKE ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + keyword + "%");
            rs = pstmt.executeQuery();

            System.out.println("\n-- 搜索结果 --");
            while (rs.next()) {
                System.out.printf("ID:%-4d 名称:%-20s 价格:%-6.2f 库存:%d\n",
                        rs.getInt("product_id"),
                        rs.getString("name"),
                        rs.getDouble("price"),
                        rs.getInt("stock"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Util.close(conn, pstmt, rs);
        }
    }
}